package com.syh.jn.scm.infrastructure.repository.impl.supplier.base.goods;

import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.util.other.ExtAssert;
import cn.redscarf.commons.util.other.ExtStringUtils;
import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.infrastructure.repository.AbstractAggregateRepository;
import com.syh.core.expction.DataModelException;
import com.syh.jn.scm.domain.supplier.entity.base.goods.GoodsCategory;
import com.syh.jn.scm.domain.supplier.repository.base.goods.GoodsCategoryRepository;
import com.syh.jn.scm.dto.supplier.base.goods.goodsCate.GoodsCategoryVo;
import com.syh.jn.scm.infrastructure.repository.model.base.goods.GoodsCategoryModel;
import com.syh.jn.scm.infrastructure.repository.utils.SQLAliasGenerateUtil;
import com.syh.jn.scm.infrastructure.wrapper.BaseResolve;
import com.syh.jn.scm.infrastructure.wrapper.ResolveToSQL;
import org.apache.ibatis.jdbc.SQL;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

@Repository
public class GoodsCategoryRepositoryImpl extends AbstractAggregateRepository<GoodsCategory, GoodsCategoryModel, Long> implements GoodsCategoryRepository {
  @Override
  public Long add(GoodsCategory goodsCategory) {
    ExtAssert.notNull(goodsCategory, "对象不存在");
    GoodsCategoryModel father = new GoodsCategoryModel();
    if (!Long.valueOf("0").equals(goodsCategory.getSupId())) {
      father = super.hibernateTemplate.get(GoodsCategoryModel.class, goodsCategory.getSupId());
      if (father == null) {
        throw new DataModelException("父级分类不存在");
      }
    }
    GoodsCategoryModel cateModel = new GoodsCategoryModel();
    ExtBeanUtils.copyProperties(goodsCategory, cateModel);
    goodsCategory.setId((Long) this.hibernateTemplate.save(cateModel));
    // 如果自定义code为空 直接使用id补充到6位
    if (ExtStringUtils.isEmpty(cateModel.getCode())) {
      cateModel.setCode(String.format("%06d", cateModel.getId()));
    }
    StringBuffer catalogCodeStr = ExtStringUtils.isEmpty(father.getCatalogCode()) ? new StringBuffer() : new StringBuffer(father.getCatalogCode()).append("-");
    cateModel.setCatalogCode(catalogCodeStr.append(goodsCategory.getId()).toString());
    return goodsCategory.getId();
  }

  @Override
  public void update(GoodsCategory goodsCategory) {
    ExtAssert.notNull(goodsCategory, "对象不存在");
    GoodsCategoryModel father = new GoodsCategoryModel();
    if (!Long.valueOf("0").equals(goodsCategory.getSupId())) {
      father = super.hibernateTemplate.get(GoodsCategoryModel.class, goodsCategory.getSupId());
      if (father == null) {
        throw new DataModelException("父级分类不存在");
      }
    }
    GoodsCategoryModel cateModel = this.hibernateTemplate.get(GoodsCategoryModel.class, goodsCategory.getId());
    ExtBeanUtils.copyProperties(goodsCategory, cateModel);
    // 如果自定义code为空 直接使用id补充到6位
    if (ExtStringUtils.isEmpty(cateModel.getCode())) {
      cateModel.setCode(String.format("%06d", cateModel.getId()));
    }
    StringBuffer catalogCodeStr = ExtStringUtils.isEmpty(father.getCatalogCode()) ? new StringBuffer() : new StringBuffer(father.getCatalogCode()).append("-");
    cateModel.setCatalogCode(catalogCodeStr.append(goodsCategory.getId()).toString());
    this.hibernateTemplate.update(cateModel);
  }

  /**
   * 根据ID查看是否有子类
   *
   * @param id
   * @return
   */
  public boolean haveSubCates(Long id) {
    StringBuffer hql = new StringBuffer("SELECT COUNT(*) FROM GoodsCategoryModel where supId =:supId");
    this.getLogger().debug(hql.toString());
    Query query = buildQuery(hql);
    query.setBigInteger("supId", BigInteger.valueOf(id));
    return ((Long) query.uniqueResult()).intValue() > 0;
  }


  @Override
  protected BaseResolve getViewWrapperResolve(Wrapper wrapper) {
    Map<String, String> params = new HashMap<>();
    params.put("name", "cate1.NAME");
    params.put("status", "cate1.STATUS");
    params.put("id", "cate1.ID");
    params.put("businessEntityId", "cate1.BUSINESS_ENTITY_ID");
    ResolveToSQL parse = new ResolveToSQL(wrapper, (propertyName) -> {
      return params.get(propertyName);
    });
    return parse;
  }

  @Override
  protected SQL getViewSql() {
    return new SQL() {{
      SELECT(
              SQLAliasGenerateUtil.aliasGenerate(GoodsCategoryModel.class, "cate1", null),
              "cate2.name as supName"
      );
      FROM("T_BASE_GOODS_CATEGORY cate1");
      LEFT_OUTER_JOIN("T_BASE_GOODS_CATEGORY cate2 on cate2.ID = cate1.SUP_ID");
    }};
  }

  @Override
  protected Class getViewObject() {
    return GoodsCategoryVo.class;
  }

}
